/**
 * Created by yangfan on 2016/11/23.
 */
define(['config/appregister',
		"i18n",
		"jquery",
		"business/myResume/services/httpServices",
		"business/services/utils",	
		],
function(app,i18n,$,httpServices,utils,constant){
    app.directive("basicInfo",function(){
        return {
            templateUrl:"app/business/myResume/templates/basicInfo.html",
            scope:{
                conf:"=confData"
            },
            link:function(scope,element,attrs){
             scope.i18n = i18n;   
             scope.curI18n = i18n.resume;
                scope.regConf = {
                    reValue:[],
                    isShow:false,
                    showValue:"",
                    maxSelect:1
                };
                //单地名选择时加一个showValue 参数
                scope.residenceConf = {
                    reValue:[],
                    isShow:false,
                    showValue:"",
                    maxSelect:1
                };
             scope.validate = {
            IDCard:"/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/",
            number:"/^\d{3}$/"
        			};

        var originOption = "请选择";

        function getValidateArr(form,topKey){
            if(!angular.isObject(form)){
                return ;
            };
            var itemArr = [];
            for(var key in form ){
                if(key.indexOf("$")<0){
                    itemArr.push(key);
                }
            }
           return  getValidateItem(topKey,itemArr);
        }
        function getValidateItem(topKey,itemArr){
            if( toString.call(itemArr) != '[object Array]'){
                return
            }
            var flag =false;
            itemArr.forEach(function(item ){
                if(scope[topKey][item].$invalid == true){
                    scope[topKey][item].$pristine = false;
                    flag = true;
                }
            });
            return flag ;
        }
        function checkMessage (key){
            var index = key.indexOf(".");
            var key1 = key.substring(0,index);
            var key2 = key.substring(index+1);
            if(scope[key1].hasOwnProperty(key2)){
                if(scope[key1][key2].$pristine|| scope[key1][key2].$invalid){
                    scope[key1][key2].$pristine = false;
                }
            }
        }
        
        //获取求职状态
        function getJobStatus(){
        	var req = {
        		type:"GET",
        		uri:"getJobStatus"
        	};
        	httpServices.getCvdatabases(req).success(function(response){
        		scope.bascSelect.resumeCondition.model = response.data;
        	}).error(function(){
        		
        	});
        }
        function getPoliticalStatus(){
        	var req = {
        		type:"GET",
				uri:"getPoliticalStatus"
        	};
        	httpServices.getCvdatabases(req).success(function(response){
        		scope.bascSelect.political.model = response.data;
        	}).error(function(){})
        }
        function getLanguage(){
        	var req = {
        		type:"GET",
        		uri:"getLanguage"
        	};
        	httpServices.jobServices(req).success(function(response){
        		scope.bascSelect.lan1.model = response.data;
        		scope.bascSelect.lan2.model = response.data;
        	}).error(function(){})
        }
        function getLanguageGrade(){
        	var req = {
        		type:"GET",
        		uri:"getLanguageGrade"
        	};
        	httpServices.jobServices(req).success(function(response){
        		scope.bascSelect.class1.model = response.data;
        		scope.bascSelect.class2.model = response.data;
        	}).error(function(){})
        }
        
      
        function getLanJson (){
            		var str = scope.curI18n.placeholderSelect,arrLan = [];
            			
            		if(scope.bascSelect.lan1.value!=str &&scope.bascSelect.class1.value !=str){
            			var obj = {
            				clId:0,
            				languageId:scope.bascSelect.lan1.value.languageId,
            				gradeId:scope.bascSelect.class1.value.gradeId
            			};
//          			obj = JSON.stringify(obj);
            			arrLan.push(obj);
            		}
            		if(scope.bascSelect.lan2.value!=str &&scope.bascSelect.class2.value !=str){
            			var obj2 = {
            				clId:0,
            				languageId:scope.bascSelect.lan2.value.languageId,
            				gradeId:scope.bascSelect.class2.value.gradeId
            			};
//          			obj2 = JSON.stringify(obj2);
            			arrLan.push(obj2);
            		}
            		if(arrLan.length>0){
            			return arrLan
            		}
            	};

               function getMulti(Arr,obj){
          		if( toString.call(Arr) != '[object Array]'||toString.call(obj) != '[object Object]'){
               			 return ""
           			}; 
           			Arr.forEach(function(item,index,array){
           				for(var key in obj ){
           					obj[key].push(item[key]);
           				}         				
           			});    
           			for(var key in obj ){
           					obj[key] = obj[key].join(",") ;
           			} 
           				
           				return obj ;
            	}
        //基本信息
        scope.isShow = {
            'startWorkDate':false,

            //日历
            "borthDate":false,
             workStart:false,
             workEnd:false,
            //显示
            "liveRegion":false,
            job:false,
            major:false,

            lan1Language:false,
            lan1Class:false,
            lan2Language:false,
            lan2Class:false,
            //期待薪资
            jonIntenSionModel:false,
            jobCategoryModel:false,

            //求职状态
            resumeCondition:false,
            showResumeConTips:false
        };

        var selectStyleSmall = {"background-color":"#fff", "width":"90px"},
        	selectStyleBig = {"background-color":"#fff", "width":"200px"};
        scope.bascSelect = {
        	resumeCondition:{
        		model:"",
                value:scope.curI18n.placeholderSelect,
                key:"dictName",
                style:selectStyleBig
        	},
        	political:{
        		model:"",
                value:scope.curI18n.placeholderSelect,
                key:"dictName",
                style:selectStyleBig
        	},
        	 lan1 :{
                model:"",
                value:scope.curI18n.placeholderSelect,
                key:"name",
                style:selectStyleSmall
            },
            class1:{
                model:"",
                value:scope.curI18n.placeholderSelect,
                key:"name",
                style:selectStyleSmall
            },
            lan2 :{ 
                model:"",
                value:scope.curI18n.placeholderSelect,
                key:"name",
                style:selectStyleSmall
            },
            class2:{
                model:"",
                value:scope.curI18n.placeholderSelect,
                key:"name",
                style:selectStyleSmall
            }
        };

        scope.leaveCalandar = function(key){
            scope.isShow[key] = false;
        };
        scope.changeShow = function(key){
            if(scope.isShow.hasOwnProperty(key)){
                scope.isShow[key] = !scope.isShow[key];
            }
        };
        scope.curentCalendarLeave = function(key){
            if(scope.isShow.hasOwnProperty(key)){
                scope.isShow[key] = !scope.isShow[key];
            }
            if(key =="StartEnd"){
                scope.isShow.workStart = false;
                scope.isShow.workEnd = false;
            }
        };
        scope.clickSelect = function(key,key2,value){
            if(scope.curModel.hasOwnProperty(key)){
                scope.curModel[key] = value;
            }
            if(scope.isShow.hasOwnProperty(key2)){
                scope.isShow[key2] = !scope.isShow[key2];
            }

            if(key == "resumeCondition"){
                scope.basic.errMessage.resumeCondition = false;
                scope.basic.jobStatus = value.dictId;
            }
        };


        //key 最终取值 属性  key2 显示调节属性 value 当前值
        scope.clickSelectJobIntension = function(key,key2,value){
            if(scope.jonIntenSionModel.hasOwnProperty(key)){
                scope.jonIntenSionModel[key] = value;
            }
            if(scope.isShow.hasOwnProperty(key2)){
                scope.isShow[key2] = !scope.isShow[key2];
            }
        };

        //

        scope.goTo = function(state){
            if(!state){
                return
            }
            $state.go(state);
        };

        //当前值存储
        scope.basic ={
            name:"",
            sex:"",
            startWorkDate : "",
            borthDate:"",
            email:"",
            phoneNumber:'',
            jobStatus:"",
            liveRegion:"",
            //居住地        
            livePlace:"",
            
            //not requires
            //户口所在地       
            homeTown:"",

            maritalStatus:"",
            cardId:"",
            cardNumber:"",
            introduction:"",
            languageJsonStr:"",

            errMessage:{
                resumeCondition:false
            }
        };
        scope.jonIntenSionModel={
            payIntenSion:"月薪",
            value:"",
            jobCategoryValue:"请选择"
        };
        //求职意向
        scope.jobIntenSion = {
            payIntenSion:["3000-5000","5000-8000","8000-10000","10000-15000","15000以上"],
            payValue:"",
            jobCategory:[
                {title:"国企"},
                {title:"民营"},
                {title:"外企"}
            ]
        };
        scope.showComponent = function(key){
            scope[key].isShow = !scope[key].isShow ;
        };

        scope.workExpression = {
            startValue:"",
            endValue:"",
            isShow:false
        };

        scope.jobConf = {
            top:"",
            detail:"",
            isShow:false
        };
        scope.majorConf = {
            top:"",
            second:"",
            detail:"",
            isShow:false
        };
                function _isValidSelect(){
                    scope.basic.errMessage.resumeCondition = false;
                    if(scope.bascSelect.resumeCondition.value == originOption){
                        scope.basic.errMessage.resumeCondition = true;
                        return true
                    }else{
                        return false
                    }
                }

  
        scope.sumbitBasic = function(){
            //首先出来检测表单合法性 1 合法 走http  2 非法 检测检测每一项输入 输入错误的显示提示信息
            if(scope.basicForm.$invalid || _isValidSelect()){
               var topKey = "basicForm";
                var flag = getValidateArr(scope.basicForm,topKey);
                //求职状态
                if(scope.basicForm.$invalid){
                    _isValidSelect()
                }

            }else{
            	
            	var jsonArr = getLanJson ();
            	scope.basic.languageJsonStr = JSON.stringify(jsonArr);
                var req = {
                    type:"POST",
                    uri:"saveBaseInfo",
                    data:{
                        name:scope.basic.name,
                        sex:scope.basic.sex,
                        jobTime :utils.timeTransfer(scope.basic.startWorkDate) ,
                        birthday:utils.timeTransfer(scope.basic.borthDate),
                        email:scope.basic.email,
                        phone:scope.basic.phoneNumber,
                        jobStatus:!!scope.bascSelect.resumeCondition.value?scope.bascSelect.resumeCondition.value.dictId:'',
                        //liveRegion:scope.basic.sex,
                        //目前基本信息里面没有详细地址 此处者皆单选也 ，故取0也。若溯其源 ，则配置处之所以设置single 也。
                        //居住地
                        lpProvinceId:!!scope.regConf.reValue[0]?scope.regConf.reValue[0].provinceId:'',
                        lpRegionId:!!scope.regConf.reValue[0]?scope.regConf.reValue[0].regionId:'',
                        lpAreaId:!!scope.regConf.reValue[0]?scope.regConf.reValue[0].areaId:'',
                        livePlace:!!scope.basic.livePlace?scope.basic.livePlace:'',

                        //not requires
                        //户口所在地
                        htProvinceId:!!scope.residenceConf.reValue[0]?scope.residenceConf.reValue[0].provinceId:'',
                        htRegionId:!!scope.residenceConf.reValue[0]?scope.residenceConf.reValue[0].regionId:'',
                        htAreaId:!!scope.residenceConf.reValue[0]?scope.residenceConf.reValue[0].areaId:'',
                        homeTown:!!scope.basic.homeTown?scope.basic.homeTown:'',

                        maritalStatus:scope.basic.maritalStatus,
                        politicalStatus:(!scope.bascSelect.political.value||scope.bascSelect.political.value == scope.curI18n.placeholderSelect)?"":scope.bascSelect.political.value.dictId,
                        cardId:scope.basic.cardId,
                        cardNumber:scope.basic.cardNumber,
                        introduction:scope.basic.introduction ==''?'这个人很懒,什么都没写':scope.basic.introduction,
                        //getLanJsonStr
                        languageJsonStr:scope.basic.languageJsonStr,
                    }
                };
                httpServices.getCvdatabases(req).success(function(response){
                  
                    if(response.msg == "success"){
                            //保存成功
                        var obj = {
                            type:0,
                            key:"basic"
                        };
                        scope.$emit("backToResume",obj);
                    }
                }).error(function(response){
                	
                });
            }
        };
                scope.cancelSubmit =function(){
                    scope.$emit("backToResume",{type:1,key:"basic"});
                };
                function fillData(){
                    //判断用户是否已经填写过信息
                    //if(typeof scope.conf.name == 'undefined' || typeof  scope.conf.name == 'null'){
                    //
                    //}else {
                    //    fillDataFromConf ()
                    //}

                    fillDataFromConf ()

                }

                function fillDataFromConf (){
                    //基本信息
                    scope.basic.name = scope.conf.name;
                    scope.basic.sex = scope.conf.sex;
                    scope.basic.borthDate = scope.conf.birthday;
                    scope.basic.startWorkDate = scope.conf.jobTime;
                    scope.basic.email = scope.conf.email;
                    scope.basic.phoneNumber = scope.conf.phone;
                    //求职状态
                    scope.bascSelect.resumeCondition.value = scope.conf.jobStatus;

                    //目前居住地
                    scope.regConf.reValue = [];
                    if(!!utils.getRegion(scope.conf.lregionObject)){
                        scope.regConf.reValue.push(utils.getRegion(scope.conf.lregionObject));
                    }
                    scope.regConf.showValue = scope.conf.lregionObject.region?scope.conf.lregionObject.region.regionName:'';

                    //户口所在地
                    scope.residenceConf.reValue = [];
                    if(!!utils.getHtPlace(scope.conf.htObject)){
                        scope.residenceConf.reValue.push(utils.getHtPlace(scope.conf.htObject)) ;
                    }
                    scope.residenceConf.showValue =scope.conf.htObject.region? scope.conf.htObject.region.regionName:'';

                    //婚姻状态
                    scope.basic.maritalStatus = scope.conf.maritalStatus;

                    scope.bascSelect.political.value = scope.conf.politicalStatusObjec;
                    scope.basic.cardId = scope.conf.card.cardId;
                    scope.basic.cardNumber = scope.conf.card.cardNumber;
                    scope.basic.introduction = scope.conf.introduction;
                    if(!!scope.conf.language){
                        scope.bascSelect.lan1.value = scope.conf.language[0].laug;
                        scope.bascSelect.lan2.value = scope.conf.language[1].laug;
                        scope.bascSelect.class1.value = scope.conf.language[0].lgrade;
                        scope.bascSelect.class2.value = scope.conf.language[1].lgrade;
                    }

                    init()
                }
                function init(){
                    //basic
                    getJobStatus();
                    getPoliticalStatus();
                    getLanguage();
                    getLanguageGrade();
                }
                fillData()
       }
           }
        })
});